package com.wxtl.action.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.JSONUtil;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.wxtl.action.vo.Json;
import com.wxtl.exception.ServiceException;
import com.wxtl.util.Constants;

/**
 * 网站统一处理Action异常并记录日志
 * @author hjc
 * @version 2011-3-25
 */
@SuppressWarnings("serial")
public class ActionExceptionInterceptor implements Interceptor {

	private static final Logger logger=Logger.getLogger(ActionExceptionInterceptor.class);
	
	public void destroy() {
	}

	public void init() {
	}

	public String intercept(ActionInvocation ai) throws Exception {
		try {
			return ai.invoke();
		} catch (Exception e) {
			e.printStackTrace();
			String msg="";
			if (e instanceof ServiceException) {
				msg=e.getMessage();
			} else {
				logger.error(e.getMessage(), e);
				msg=Constants.DEFAULT_EX_MSG;
			}
			
			HttpServletRequest request = (HttpServletRequest) ai.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ai.getInvocationContext().get(ServletActionContext.HTTP_RESPONSE);
			//System.out.println(ai.getResultCode());
			if(ai.getResultCode()==null){//代表ajax请求
				request.setCharacterEncoding("UTF-8");
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json;charset=UTF-8");
				
				PrintWriter out=response.getWriter();
				Json json=new Json();
				json.setSuccess(false);
				json.setMsg(msg);
				
				out.print(JSONUtil.serialize(json));
				out.flush();
				out.close();
				return null;
			}
			
			//非ajax请求
			throw new RuntimeException(msg);
			

		}
	}
}
